package com.hong.taotaomall.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hong.taotaomall.common.CustomException;
import com.hong.taotaomall.entity.Result;
import com.hong.taotaomall.entity.User;
import com.hong.taotaomall.service.IUserService;
import com.hong.taotaomall.utils.RandomUserInfoUtlis;
import com.hong.taotaomall.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户信息 前端控制器
 * </p>
 *
 * @author hong
 * @since 2023-03-25
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/sendMSG")
    public Result<String> sendMSG(@RequestBody User user) {
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)) {
            String code = ValidateCodeUtils.generateValidateCode(6).toString();
            log.info("验证码:  {}", code);
            //            TencentCloudApi.sendSmg(code,86+phone);
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            return Result.success("短信发送成功");
        }
        return Result.success("短信发送失败");
    }

    @RequestMapping("/logout")
    public Result<String> logout(HttpSession session) {
        session.removeAttribute("user");
            return Result.success("退出成功");
    }

    @RequestMapping("/login")
    public Result<User> login(@RequestBody User user, HttpSession session) {

        String password = user.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUsername, user.getUsername());

        User one = userService.getOne(lambdaQueryWrapper);
        if (one == null) {
            return Result.error("登录失败用户不存在");
        }
        if (!one.getPassword().equals(password)) {
            return Result.error("登录失败,密码错误");
        }
        if (one.getStatus() == 0) {
            return Result.error("账号已禁用");
        }
        session.setAttribute("user", one.getId());
        return Result.success(one);
    }

    @RequestMapping("/login1")
    public Result<User> login1(@RequestBody Map map, HttpSession session) {
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();

        Object codeValid = redisTemplate.opsForValue().get(phone);
        if (codeValid == null) {
            return Result.error("redis连接误");
        }
        LambdaQueryWrapper<User> phoneQueryWrapper = new LambdaQueryWrapper<>();
        phoneQueryWrapper.eq(User::getPhone, phone);
        User one = userService.getOne(phoneQueryWrapper);
        if (one == null) {
            return Result.error("登录失败用户不存在");
        }
        if (!codeValid.equals(code)) {
            return Result.error("登录失败,验证码错误");
        }
        if (one.getStatus() == 0) {
            return Result.error("账号已禁用");
        }
        session.setAttribute("user", one.getId());
        redisTemplate.delete(phone);
        return Result.success(one);
    }

    @RequestMapping("/register")
    public Result<String> register(@RequestBody Map map) {
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
        String username = map.get("username").toString();
        String password = map.get("password").toString();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        Object codeValid = redisTemplate.opsForValue().get(phone);
        if (codeValid == null) {
            return Result.error("验证码为空");
        }
        LambdaQueryWrapper<User> phoneQueryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<User> nameQueryWrapper = new LambdaQueryWrapper<>();
        phoneQueryWrapper.eq(User::getPhone, phone);

        nameQueryWrapper.eq(User::getUsername, username);

        User one = userService.getOne(phoneQueryWrapper);
        if (one != null) {
            return Result.error("手机号已被使用,换个试试吧");
        }
        one = userService.getOne(nameQueryWrapper);
        if (one != null) {
            return Result.error("用户名已被使用,换个试试吧");
        }
        if (!codeValid.equals(code)) {
            return Result.error("注册失败,验证码错误");
        }
        redisTemplate.delete(phone);
        one = new User();
        one.setUsername(username);
        one.setPhone(phone);
        one.setPassword(password);
        one.setIdNumber(RandomUserInfoUtlis.getRandomIdNumber());
        userService.save(one);
        return Result.success("注册成功");
    }
}
